//
//  ZByteOperations.h
//  Part of Z-Way.C library
//
//  Created by Alex Skalozub on 2/4/12.
//  Based on Z-Way source code written by Christian Paetz and Poltorak Serguei
//
//  Copyright (c) 2012 Z-Wave.Me
//  All rights reserved
//  info@z-wave.me
//
//  This source file is subject to the terms and conditions of the
//  Z-Wave.Me Software License Agreement which restricts the manner
//  in which it may be used.
//

#ifndef zway_byte_operations_h
#define zway_byte_operations_h

#ifndef MAX
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#endif
#ifndef MIN
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#endif

#define clear_bitmask(bitmask) memset((bitmask), 0, 32)

#define SET_BIT(bitmask, index) ((ZWBYTE*)(bitmask))[(index) / 8] |= (ZWBYTE)(1 << ((index) % 8))
#define CLR_BIT(bitmask, index) ((ZWBYTE*)(bitmask))[(index) / 8] &= (ZWBYTE)(~(1 << ((index) % 8)))
#define TEST_BIT(bitmask, index) (((ZWBYTE*)(bitmask))[(index) / 8] & (ZWBYTE)(1 << ((index) % 8)))
#define TEST_BIT_N(bitmask, index, bitmask_size) (((size_t)index < (size_t)bitmask_size * 8) && TEST_BIT(bitmask, index))

#define SET_BIT_BE(bitmask, index) ((ZWBYTE*)(bitmask))[(index) / 8] |= (ZWBYTE)(1 << (7 - (index) % 8))
#define CLR_BIT_BE(bitmask, index) ((ZWBYTE*)(bitmask))[(index) / 8] &= (ZWBYTE)(~(1 << (7 - (index) % 8)))
#define TEST_BIT_BE(bitmask, index) (((ZWBYTE*)(bitmask))[(index) / 8] & (ZWBYTE)(1 << (7 - (index) % 8)))


ZWEXPORT_PRIVATE int _bytes_to_int(const ZWBYTE *bytes, ZWBYTE length);
ZWEXPORT_PRIVATE int _bytes_to_int_le(const ZWBYTE *bytes, ZWBYTE length);
static inline ZWWORD _zbytes_to_word(const void *const ptr)
{
	return _bytes_to_int((const ZWBYTE *)ptr, 2);
}

ZWEXPORT_PRIVATE void _int_to_bytes(int value, ZWBYTE *bytes, ZWBYTE length);
ZWEXPORT_PRIVATE void _int_to_bytes_le(int value, ZWBYTE *bytes, ZWBYTE length);

ZWEXPORT void _array_bits_shift(ZWBYTE *array, size_t bits, ZWBYTE shift);

ZWEXPORT_PRIVATE char *_int_array_to_string(const int *num, size_t length);
ZWEXPORT_PRIVATE char *_bytes_to_string(const ZWBYTE *bytes, size_t length);
ZWEXPORT_PRIVATE ZWSTR _bytes_to_string_ext(const ZWBYTE *const bytes, const size_t length, const ZWBOOL withBracesAndSpaces);
ZWEXPORT_PRIVATE ZWBOOL _string_to_bytes(const char *string, ZWBYTE **bytes, size_t *size);

ZWEXPORT_PRIVATE ZWBYTE _float_to_bytes(float value, ZWBYTE *bytes, ZWBYTE *detectedPrecision);

#endif
